import {defineStore} from 'pinia'

import request from '@/utils/request'
// 导入泛型接口
import {ApiRes,categoryItem,TopCategory,SubCategory } from '@/types/data'
// 当result给的类型不确定时,使用泛型接口
import { topCategory } from '@/store/constants'

const  defaultCategory = topCategory.map((item) => {
    return {
        name : item 
    }
})
export default defineStore("category",{
    // 存储数据
    state() {
        return {
            categoryList : defaultCategory  as  categoryItem[],
            topCategory: {} as TopCategory,
            subCategory: {} as SubCategory,
        }
    },
    // 计算属性
    getters : {

    },
    // 修改state里面的数据
    actions : {
       async getAllCategory() {
        // 发送ajax请求,获取头部分类列表,所有分类
            const res = await request.get<ApiRes<categoryItem[]>>("/home/category/head")
            // console.log(res)
            this.categoryList = res.data.result
        },

        // 获取一级分类数据
       async getTopCategory(id : string) {
            // const res = await request.get("/category?id"+id)
            const res = await request.get<ApiRes<TopCategory>>("/category",{params:{id}})
           // console.log(res)
            this.topCategory = res.data.result
        },
        // 获取二级分类数据
        async getSubFilter(id: string) {
            const res = await request.get<ApiRes<SubCategory>>(
              '/category/sub/filter',{params: {id}})
            this.subCategory = res.data.result
          },
    }
})